package com.jackstraw.commoncode.exception;

import lombok.Data;

/**
 * 所在包：com.example.demo.exception
 * 文件名： 自定义系统异常
 * 版权：jackstraw.
 * 项目：demo
 * 功能描述：
 * 修改人：稻草人
 * 修改时间：2022-04-02 11:30
 */
@Data
public class SystemException extends RuntimeException {

    /**
     * 异常记录空格
     */
    private static final String ERROR_SPACE = "    ";
    /**
     * 首条异常前缀
     */
    private static final String FIRST_ERROR_MSG_PREFIX = ERROR_SPACE + ">>> ";
    /**
     * 非首条异常前缀
     */
    private static final String NOT_FIRST_ERROR_MSG_PREFIX = ERROR_SPACE + ">>  ";

    /**
     * 最近一次异常信息
     */
    private String latestErrorMsg;

    /**
     * 自定义异常描述信息
     */
    private String customErrorMsg;

    /**
     * 原始异常信息
     */
    private String origErrorMsg;

    /**
     * 构建异常信息封装对象
     * @param customErrorMsg 自定义提示信息
     * @param e 原始异常提示信息
     */
    public SystemException(String customErrorMsg, Exception e) {
        super(customErrorMsg);
        if (e instanceof SystemException) {
            SystemException systemException = (SystemException) e;
            this.customErrorMsg = systemException.getCustomErrorMsg();
            this.origErrorMsg = systemException.getOrigErrorMsg();
        } else {
            this.origErrorMsg = e.getMessage();
        }
        appendCustomErrorMsg(customErrorMsg);
        this.latestErrorMsg = customErrorMsg;
    }

    /**
     * 追加自定义异常描述信息
     * @param customErrorMsg
     */
    private void appendCustomErrorMsg(String customErrorMsg) {
        if (this.customErrorMsg == null || this.customErrorMsg.trim().length() == 0) {
            this.customErrorMsg = "    >>> " + customErrorMsg;
        } else {
            this.customErrorMsg = "    >>  " + customErrorMsg + System.lineSeparator() + this.customErrorMsg;
        }
    }
}
